﻿using System;
using System.Collections.Generic;
using MemoryAddress = System.UInt16;

namespace ManoMachine.Assembler.Core
{
    /// <summary>
    /// Symbol table: Associates symbols with memory addresses.
    /// </summary>
    public class SymbolTable
    {
        readonly Dictionary<string, MemoryAddress> _symbols = new Dictionary<string, MemoryAddress>();

        /// <summary>
        /// Insert a new symbol.
        /// </summary>
        /// <param name="symbol">The symbol.</param>
        /// <param name="address">The address of the symbol.</param>
        public void Insert(string symbol, MemoryAddress address)
        {
            _symbols.Add(symbol.ToUpper(), address);
        }

        /// <summary>
        /// Checks the existence of the symbol.
        /// </summary>
        /// <param name="symbol"></param>
        /// <returns></returns>
        public bool Contains(string symbol)
        {
            return _symbols.ContainsKey(symbol.ToUpper());
        }

        /// <summary>
        /// Retrieve the value of a symbol if it's exists.
        /// <remarks>
        /// Null will be returned in case the symbol is not exist.
        /// </remarks>
        /// </summary>
        /// <param name="symbol">symbol</param>
        /// <returns>The memory address of the symbol if the symbol is exist</returns>
        public Nullable<MemoryAddress> GetAddress(string symbol)
        {
            string uSymbol = symbol.ToUpper();
            return this.Contains(uSymbol) ? (MemoryAddress?) null : _symbols[uSymbol];
        }
    }
}
